package com.jomoo.css.common.core.bean.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Map;

@Slf4j
@Service
@Lazy(false)
public class SpringUtil implements ApplicationContextAware {

    @Autowired
    private static ApplicationContext context;

    public static ApplicationContext getContext() {
        return context;
    }

    public static <X> X getBean(Class beanclass) {
        return (X) getContext().getBean(beanclass);
    }

    public static <X> X getBean(String beanname) {
        return (X) getContext().getBean(beanname);
    }

    public static Collection getBeansOfType(Class type) {
        return context.getBeansOfType(type).values();
    }

//    public String getAppRootPath() {
//        if (WebApplicationContext.class
//                .isAssignableFrom(this.context.getClass())) {
//            WebApplicationContext wac = (WebApplicationContext) this.context;
//            String appRootPath = wac.getServletContext().getRealPath("/");
//            if (appRootPath.endsWith("/") || appRootPath.endsWith("\\")) {
//                appRootPath = appRootPath
//                        .substring(0, appRootPath.length() - 1);
//            }
//            return appRootPath;
//        } else {
//            return null;
//        }
//    }

    public static <T> Map<String, T> getBeansOfTypeMap(Class<T> type) {
        return context.getBeansOfType(type);
    }

    public void setApplicationContext(ApplicationContext contex)
            throws BeansException {
        this.context = contex;
    }

}